﻿$(document).ready(function () {
    var timer;
    var pdfTimer;

    $("#btnRenderPages").click(function () {
        var mainDialog = updateDialog("בחירת איכות PDF", "190", "500");

        //Invoke AJAX method to show the SetQuality dialog
        $.get(pathPrefix + "Albums/SetPdfQuality", null, function (result) {
            mainDialog.html(result);
        }, "html");
    });

    $("#StartRenderTask").live("click", function () {
        $.validator.unobtrusive.parse($("#frmSetPdfQuality"));

        if ($("#frmSetPdfQuality").valid()) {
            var data = {
                "id": $("#AlbumId").val(),
                "quality": $("#Quality").val()
            };

            var mainDialog = updateDialog("הפקת גרסת הדפסה", "210", "700");

            //Invoke AJAX method to invoke the render functionality
            $.post(pathPrefix + "Albums/Render", data, function (result) {
                mainDialog.html(result);

                //send AJAX requests to get the current render pages count
                timer = window.setTimeout(ShowRenderStatusInDialog, 1000);
            }, "html");
        }
    });

    $("#ClosePdfDialog").live("click", function () {
        closeDialog();
    });

    $("#btnShowRenderDlg").click(function () {
        $.get(pathPrefix + "Render/IsRendering", function (result) {
            if (!result) {
                alert("לא מתבצע רנדור");
            }
            else {
                $.post(pathPrefix + "Albums/GetRenderDialog", { "id": 1 }, function (result) {
                    var mainDialog = updateDialog("התקדמות רנדור", "210", "700");
                    mainDialog.html(result);

                    //send AJAX requests to get the current render pages count
                    timer = window.setTimeout(ShowRenderStatusInDialog, 1000);
                }, "html");
            }
        }, "json");
    });


    function ShowRenderStatusInDialog() {

        //Invoke ajax method to get the render current status and show in the dialog

        $.post(pathPrefix + "Albums/GetRenderStatus", { "id": $("#AlbumId").val() }, function (result) {

            $("#divMainDialog #message").html(result.RenderedPagesCount + " מתוך " + result.AlbumPages + " עמודים מוכנים לדפוס.");

            //update the progress bar
            var percentageComplete = (result.RenderedPagesCount / result.AlbumPages) * 100;
            $("#divMainDialog #progress").html(percentageComplete.toFixed(0) + "%");
            $("#divMainDialog #progress").animate({ "width": percentageComplete + "%" }, function () {
                //if there are pages left to be rendered
                if (result.RenderedPagesCount < result.AlbumPages) {
                    //create another timer
                    window.clearTimeout(timer);
                    timer = null;
                    timer = window.setTimeout(ShowRenderStatusInDialog, 4000);
                }
                //if all pages completed
                else {
                    GeneratePDF();
                }
            });
        }, "json");
    }

    function GeneratePDF() {
        //change the current render stage
        $("ul#RenderStages li.current").removeClass("current");
        $("ul#RenderStages li:eq(1)").addClass("current");

        //update the message and progress bar
        $("#divMainDialog #message").html("הכנת עמודי האלבום לדפוס הושלמה.<br />כעת מופק קובץ ה-PDF של האלבום...");
        $("#divMainDialog #progress").html("0%");
        $("#divMainDialog #progress").css({ "width": "0%" });

        //send AJAX requests to get the current pdf pages count
        pdfTimer = window.setTimeout(ShowPdfStatus, 1000);
    }

    function ShowPdfStatus() {
        //Invoke ajax method to get the pdf current status and show in the dialog
        $.post(pathPrefix + "Albums/GetPdfStatus?rand=" + Math.random(), { "id": $("#AlbumId").val() }, function (result) {
            var percentageComplete = result.Percentage;

            if (percentageComplete != null) {
                $("#divMainDialog #progress").html(percentageComplete.toFixed(0) + "%");
                $("#divMainDialog #progress").animate({ "width": percentageComplete + "%" }, function () {
                    //if pdf not completed
                    if (percentageComplete < 100) {
                        //create another timer
                        window.clearTimeout(pdfTimer);
                        pdfTimer = null;
                        pdfTimer = window.setTimeout(ShowPdfStatus, 3000);
                    }
                    //if pdf completed
                    else {
                        //change the current render stage
                        $("ul#RenderStages li.current").removeClass("current");
                        $("ul#RenderStages li:eq(2)").addClass("current");

                        $("#divMainDialog #message").html(result.Message);
                        $("#divMainDialog #progressBar").hide();
                        $("#divMainDialog .loadingImage").hide();

                        ShowRenderStatus();
                        InitPrintVersions();
                        $("#HasRender").val(true);
                    }
                });
            }
        }, "json");
    }

    var albumPages;
    var renderedPagesCount;

    function ShowRenderStatus() {
        //Invoke ajax method to get the render current status and show in the dialog
        $.post(pathPrefix + "Albums/GetRenderStatus?rand=" + Math.random(), { "id": $("#AlbumId").val() }, function (result) {
            albumPages = result.AlbumPages;
            renderedPagesCount = result.RenderedPagesCount;

            if (albumPages > 0) {
                var percentageComplete = (renderedPagesCount / albumPages) * 100;
                if (percentageComplete.toString().indexOf('.') >= 0) {
                    percentageComplete = percentageComplete.toFixed(0);
                }
                $("#albumRenderStatus").html("<strong>" + percentageComplete + "%</strong> מהעמודים מוכנים לדפוס");
            }

            GetRenderVariables();
        }, "json");
    }

    /* Render Indicators (IsRenderProccessEmpty and IsRenderRun)
    ------------------------------------------------------------*/

    function GetRenderVariables() {
        //get the render variables and update the relevant labels
        $.get(pathPrefix + "Albums/GetRenderVariables", null, function (result) {
            var disableRenderButton = false;

            if (result.IsRenderProccessEmpty == false) {
                $("#IsRenderProccessEmpty").addClass("false").html("רינדור מתבצע...");
                disableRenderButton = true;
            }
            else {
                $("#IsRenderProccessEmpty").removeClass("false").html("תור הרינדור פנוי");
            }

            if (result.IsRenderRun == false) {
                $("#IsRenderRun").addClass("false").html("שירות הרינדור לא פועל");
                disableRenderButton = true;
            }
            else {
                $("#IsRenderRun").removeClass("false").html("שירות הרינדור פועל");
            }

            var albumHasRender = $("#HasRender").val();

            if (disableRenderButton) {
                //disable the "Render Pages" button
                $("#btnRenderPages").attr("disabled", "disabled").addClass("disabled").attr("title", "לא ניתן לבצע כעת");
            }
            else {
                //enable the "Render Pages" button
                $("#btnRenderPages").removeAttr("disabled").removeClass("disabled").removeAttr("title");
            }

            //if there are pages left to be rendered
            if ((renderedPagesCount < albumPages || albumHasRender == "false")) {
                $("#allPagesRendered").hide();
            }
            //all pages have been rendered
            else {
                $("#allPagesRendered").show();
            }
        }, "json");
    }

    ShowRenderStatus();

    window.setInterval(function () {
        if ($("#divMainDialog:visible").length == 0) {
            GetRenderVariables();
        }
    }, 10000);

    /* Print Versions Init 
    -----------------------*/

    function InitPrintVersions() {
        $("#PrintVersions tr:not(:first)").remove();

        var data = {
            "id": $("#AlbumId").val()
        };

        //Invoke AJAX method to get all the Print Versions of this album
        $.get(pathPrefix + "Albums/GetAlbumPrintVersions", data, function (PrintVersions) {
            for (var i = 0; i < PrintVersions.length; i++) {
                var row = $("#printVersionRowTemplate").tmpl(PrintVersions[i]).appendTo("#PrintVersions");

                //set the status of the row
                var statusId = PrintVersions[i].AlbumPrintVersionStatusId;
                row.find("[name='AlbumPrintVersionStatusId']").val(statusId);

                if (PrintVersions[i].PdfSentDate != null) {
                    row.find(".IsPdfSent").prop("checked", true);
                    row.find("[name='PdfSentDate']").show();
                }
                if (PrintVersions[i].PrintSentDate != null) {
                    row.find(".IsPrintSent").prop("checked", true);
                    row.find("[name='PrintSentDate']").show();
                }
                if (PrintVersions[i].ShowToAlbumEditor) {
                    row.find(".ShowToAlbumEditor").prop("checked", true);
                }
            }

            if (PrintVersions.length > 0) {
                $("#PrintVersions").show();
                $("#updatePrintVersionsContainer").show();
            }

            setDatepicker();

            tableAltRows();
        }, "json");
    }

    InitPrintVersions();
});